package edu.tjut.web;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import edu.tjut.dao.CustomerDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import edu.tjut.dao.CustomerDao;
import edu.tjut.domain.Customer;

@Controller
public class CustomerController {
	@Autowired
	private CustomerDao customerDao;
	
	@PostMapping("/")
	@ResponseBody
	public List<Customer> customerTest1(@RequestParam String domain, @RequestParam BigDecimal creditLimit) {
		return customerDao.findByEmail_ValueContainingAndCreditLimitAmountGreaterThanEqual(domain, creditLimit);
	}
	
	@GetMapping("/page")
	@ResponseBody
	public List<Customer> page(@RequestParam int page, @RequestParam int size) {
		Sort s = Sort.by(Order.desc("creditLimit.amount"));
		return customerDao.findAll(PageRequest.of(page, size, s)).stream().collect(Collectors.toList());
	}
	
	@GetMapping("/count")
	@ResponseBody
	public long count(@RequestParam String domain) {
		return customerDao.countByEmailValueContaining(domain);
	}
	
	@GetMapping("/delete")
	@ResponseBody
	@Transactional
	public long delete(@RequestParam String domain) {
		return customerDao.deleteByEmailValueContaining(domain);
	}

	@GetMapping("/remove")
	@ResponseBody
	@Transactional
	public List<Customer> remove(@RequestParam String domain) {
		return customerDao.removeByEmailValueContaining(domain);
	}
	
	@GetMapping("/allcustomers")
	public String all(Map<String, Object> model) {
		model.put("customers", customerDao.findAll(Sort.by(Order.desc("creditLimit.amount"))));
		return "customer";
	}
}
